<?php

namespace App\Models\Rbac;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class Menu extends BaseModel
{

    protected $fillable = ['title','name', 'slug', 'path', 'component', 'icon', 'parent_id', 'type', 'hidden', 'sort'];

    protected $appends = ['meta'];
    protected $casts = [
        'hidden' => 'boolean', // 如果 hidden 是布尔字段
    ];

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_menus');
    }

    protected function meta(): Attribute
    {
        Log::info($this->title.'--',$this->hidden);
        $meta = [
            'title' => $this->title,
            'hidden' => boolval($this->attributes['hidden']),
            'icon' => $this->icon,
        ];
        return Attribute::make(
            get: fn ($value) => $meta
        );
    }

    /**
     * 获取子分类
     */
    public function children()
    {
        return $this->hasMany(Menu::class,'parent_id');
    }


    public static function getAuthMenu()
    {
        self::query()->whereNull('parent_id')
            ->orderBy('sort', 'asc')
            ->with('children')->get();
    }
}
